#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_icon=C:\Program Files (x86)\AutoIt3\Icons\filetype-blank.ico
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Res_Description=DVDID
#AutoIt3Wrapper_Res_Fileversion=1.0.0.0
#AutoIt3Wrapper_Res_Language=1033
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
; Example script, showing the usage of COM Event functions.
; Requires at least AutoIt beta version 3.1.1.104 !
;
; See also: http://msdn.microsoft.com/workshop/browser/webbrowser/reference/objects/internetexplorer.asp

; We use a very simple GUI to show the results of our Events.
#include "GUIConstantsEx.au3"
#include <IE.au3>
#include <File.au3>
#include <Array.au3>
#Include <GuiListView.au3>

Dim $filearr
Global $oIE
Global $loggedin = False
Global $MovieFileArr[1][2]
Global $batchmode = False


#Region ### START Koda GUI section ### Form=c:\program files\autoit3\scite\koda\forms\form1.kxf
$Form1 = GUICreate("Search DVDID", 547, 433, 340, 232)
$Group1 = GUICtrlCreateGroup("", 8, 8, 529, 417)
$List1 = _GUICtrlListView_Create($Form1,"Title(s) Found|Path to file", 18, 45,249,305,BitOr($LVS_REPORT,$LVS_SINGLESEL,$LVS_SHOWSELALWAYS))
_GUICtrlListView_SetExtendedListViewStyle($List1,BitOr($LVS_EX_CHECKBOXES, $LVS_EX_FULLROWSELECT))

_GUICtrlListView_SetColumnWidth($list1, 0, $LVSCW_AUTOSIZE_USEHEADER)
_GUICtrlListView_SetColumnWidth($list1, 1, $LVSCW_AUTOSIZE_USEHEADER)

$Search = GUICtrlCreateButton("Search", 16, 384, 57, 25, 0)
GuiCtrlSetState(-1, $GUI_DISABLE)
$FileImpButton = GUICtrlCreateButton("Import File",73, 384, 57, 25, 0)
$DirImpButton = GUICtrlCreateButton("Import Dir",130, 384, 57, 25, 0)
$SaveXML = GUICtrlCreateButton("SaveXML", 187, 384, 57, 25, 0)
$Clear = GUICtrlCreateButton("Clear", 244, 384, 57, 25, 0)
;$Input = GUICtrlCreateInput("", 20, 360, 225, 21)

$UserInput = GUICtrlCreateInput("", 440, 360, 81, 21)
$PassInput = GUICtrlCreateInput("", 440, 384, 81, 21, 0x0020)
$UserLabel = GUICtrlCreateLabel("Username:", 376, 360, 55, 17)
$PassLabel = GUICtrlCreateLabel("Password:", 376, 384, 53, 17)

$List2 = _GUICtrlListView_Create($Form1,"Available Titles                                                          |", 278, 45,249,305,BitOr($LVS_REPORT,$LVS_SINGLESEL))
_GUICtrlListView_SetExtendedListViewStyle($List2,BitOr($LVS_EX_CHECKBOXES,$LVS_EX_FULLROWSELECT))
_GUICtrlListView_SetColumnWidth($list2, 0, $LVSCW_AUTOSIZE_USEHEADER)
_GUICtrlListView_SetColumnWidth($list2, 1, $LVSCW_AUTOSIZE_USEHEADER)
_GUICtrlListView_HideColumn($list2, 1)
$SearchLabel = GUICtrlCreateLabel("Search Term", 24, 22, 65, 17)
$SearcLabel = GUICtrlCreateLabel("Search Results", 272, 22, 76, 17)
GUICtrlCreateGroup("", -99, -99, 1, 1)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###



Opt("OnExitFunc", "OnExit")

While 1
	$nMsg = GUIGetMsg(1)
	Switch $nMsg[1]
	Case $Form1
			Switch $nMsg[0]
			Case $GUI_EVENT_CLOSE
				Exit
			Case $Search

				Select
					Case _GuiCtrlListView_GetItemCount($list1) = 1
						Search(_GUICtrlListView_GetItemText($List1,0))
					Case _GuiCtrlListView_GetItemCount($list1) > 1
						$selitem = _GUICtrlListView_GetSelectedIndices($list1,True)
						If Not _GUICtrlListView_GetItemChecked($list1,$selItem[1]) then
							For $i = ($selItem[1] +1) to _GuiCtrlListView_GetItemCount($list1)
								If _GUICtrlListView_GetItemChecked($list1,$i) then
									_GUICtrlListView_SetItemSelected($list1, $i)
									Search(_GUICtrlListView_GetItemText($List1,$i))
									ExitLoop
								Endif
							Next
						Else
							Search(_GUICtrlListView_GetItemText($List1,$selitem[1]))
							$selItem = ''
						Endif


						;Endif
				EndSelect
					#cs
					If Not $batchmode then
						Msgbox(48,'Error', 'Please enter a disc title to search for.')
					Else
						if _GUICtrlListView_GetItemCount($List2) > 0 then
						For $i = 0 to _GuiCtrlListView_GetItemCount($list1)
							BatchSearch(_GUICtrlListView_GetItemText($List1, $i))
						Next
						Endif
					Endif
				#ce
			Case $SaveXML
				Dim $index
				For $i = 0 to _GUICtrlListView_GetItemCount($List2)
					$index +=_GUICtrlListView_GetItemChecked($List2,$i)
				Next
				Select
				Case $index > 1
					Msgbox(0,'Error', 'Only one selection may be saved at a time')
				Case $index = 1
					;Msgbox(0,'', $index)
					For $i = 0 to _GUICtrlListView_GetItemCount($List2)
						if _GUICtrlListView_GetItemChecked($List2,$i) = 1 Then

							$texturl =_GUICtrlListView_GetItemText($List2, $i,1)
							makeXML($textUrl)
							If _GUICtrlListView_GetItemCount($list1) > 0 Then

							Endif
							ExitLoop
						Endif
					Next

				Case $index =0
					Msgbox(0,'Error', 'Nothing is selected')
				EndSelect
				$index = ''
			Case $Clear
				_GUICtrlListView_DeleteAllItems($List1)
				_GUICtrlListView_DeleteAllItems($List2)
				_GUICtrlListView_SetColumnWidth($list1, 0, $LVSCW_AUTOSIZE_USEHEADER)
				_GUICtrlListView_SetColumnWidth($list1, 1, $LVSCW_AUTOSIZE_USEHEADER)
				_GUICtrlListView_SetColumnWidth($list2, 0, $LVSCW_AUTOSIZE_USEHEADER)
				_GUICtrlListView_SetColumnWidth($list2, 1, $LVSCW_AUTOSIZE_USEHEADER)
				GuiCtrlSetState($Search, $GUI_ENABLE)
			Case $DirImpButton
				$scandir = FileSelectFolder("Choose the folder you would like to scan for",'My Computer')
				If not @error then
				$batchmode = True
				FileSearch($Scandir)
				If _GuiCtrlListView_GetItemCount($List1) > 0 then
					GuiCtrlSetState($Search, $GUI_ENABLE)
				Else
					GuiCtrlSetState($Search, $GUI_DISABLE)
				Endif
				_GUICtrlListView_SetColumnWidth($List1, 0, $LVSCW_AUTOSIZE);Resize the list view
				_GUICtrlListView_SetColumnWidth($List1, 1, $LVSCW_AUTOSIZE);Resize the list view
				_GUICtrlListView_SetItemSelected($list1,0)
					GuiCtrlSetState($list1, $GUI_FOCUS)
				Endif
			Case $FileImpButton
				$filescan = FileOpenDialog("Choose the movie file you would like to import", "My Computer","Movie files (*.avi;*.dvr-ms;*.vob;*.mkv;*.mts;*.mpg)",7)
				If Not @error  and $filescan <> '' Then
					If StringInStr($filescan,'|') Then
						$filescanarr = StringSplit($filescan, '|')
						For $i = 2 to $filescanarr[0]
							$fTitle = Stringleft($filescanarr[$i],StringInStr($filescanarr[$i],'.')-1)
							_GUICtrlListView_AddItem($list1,$fTitle)
							_GUICtrlListView_AddSubItem($list1,_GUICtrlListView_GetItemCount($list1) -1,$filescanarr[1] & '\' & $filescanarr[$i],1)
							_GUICtrlListView_SetColumnWidth($List1, 0, $LVSCW_AUTOSIZE);Resize the list view
							_GUICtrlListView_SetColumnWidth($List1, 1, $LVSCW_AUTOSIZE);Resize the list view
						Next
					Else
						$fTitle = StringMid($filescan, StringInStr($filescan, '\', -1,-1) +1, (StringInStr($filescan, '.', -1,-1) -1) - (StringInStr($filescan, '\', -1,-1)))
						_GUICtrlListView_AddItem($list1,$fTitle)
						_GUICtrlListView_AddSubItem($list1,_GUICtrlListView_GetItemCount($list1) -1,$filescan,1)
						_GUICtrlListView_SetColumnWidth($List1, 0, $LVSCW_AUTOSIZE);Resize the list view
						_GUICtrlListView_SetColumnWidth($List1, 1, $LVSCW_AUTOSIZE);Resize the list view
					Endif
					If _GuiCtrlListView_GetItemCount($List1) > 0 then
						GuiCtrlSetState($Search, $GUI_ENABLE)
					Else
						GuiCtrlSetState($Search, $GUI_DISABLE)
					Endif
					_GUICtrlListView_SetItemChecked($List1, _GUICtrlListView_GetItemCount($list1) -1)
					_GUICtrlListView_SetItemSelected($list1,0)
					GuiCtrlSetState($list1, $GUI_FOCUS)
				Endif
				$fTitle = ''
				$filescan = ''
				$filescanarr = ''
		EndSwitch
	Case Else
		#cs
		Switch $nMsg[0]
			Case $GUI_EVENT_CLOSE
				Exit
			Case $ContButton
				$x = 0
				For $i = 0 to _GUICtrlListView_GetItemCount($list2)
					If _GUICtrlListView_GetItemChecked($list2, $i) = 1 then
						Redim $MovieFileArr[$x + 1][2]
						$MovieFileArr[$x][0] = _GUICtrlListView_GetItemText($list2, $i);MovieTitle
						$MovieFileArr[$x][1] = _GUICtrlListView_GetItemText($list2, $i,1);Path
						$x += 1

					Endif
				Next
				_ArrayDisplay($MovieFileArr, 'MovieFileArr')
			Case $CancelButton

	EndSwitch
	#ce
	EndSwitch
WEnd


Func Search($term)
	Local $pagearr, $rootUrl = 'http://www.dvdxml.com', $dUrl, $downloadUrl, $urlarr[1][2]
If not $loggedin then
	Login()
	If @error then
		;_GUICtrlListView_DeleteAllItems($list1)
		Msgbox(48, 'Incorrect Login', 'Login has failed, please verify your login credentials and try again.')
		Return
	Endif
Endif

_GUICtrlListView_DeleteAllItems($list2)
SplashTextOn("Search", 'Searching for titles matching ' & $term & '...',500,50,-1,-1,32,'Arial',10)
$term = Stringreplace($term, ' ','+')
$oIE.Navigate("http://www.dvdxml.com/search.php?q="& $term &"&t=1")
_IELoadWait($oIE)
$html = _IEBodyReadHTML($oIE)
$pagearr = StringSPlit($html, @CR)
;_ArrayDisplay($pagearr, 'pagearr')


	For $i = 1 to $pagearr[0]
		If StringInStr($pagearr[$i], '<A href="/download/view.php?xml_id=') Then
			;Msgbox(0,'',$pagearr[$i])
			;"<a href='/download/view.php?xml_id=61239'>The Adventures of Indiana Jones: The Complete DVD Movie Collection [WS] [4 Discs]</a></"
			$dUrl = StringMid($pagearr[$i], StringInStr($pagearr[$i],'<a href="') + 9, (StringInStr($pagearr[$i], '">')) - (StringInStr($pagearr[$i],'<a href="') + 9))
			$title = Stringreplace(StringReplace(StringMid($pagearr[$i],StringInStr($pagearr[$i], '">') + 2, (StringInStr($pagearr[$i], '</A></')) -(StringInStr($pagearr[$i], '">') + 2)),"&amp;", ''), "</A>", "")
			$downloadUrl = $rootUrl & $dUrl
			;_GUICtrlListView_AddItem($List2, $title)
			;_GUICtrlListView_AddSubItem($List2, _GUICtrlListView_GetItemCount($List2) -1, $downloadUrl, 1)
			Redim $urlarr[Ubound($urlarr) +1][2]
			$urlarr[Ubound($urlarr)-1][0] = $title
			$urlarr[Ubound($urlarr)-1][1] = $downloadUrl
			$title = ''
			$downloadUrl = ''
		Endif
		If StringInStr($pagearr[$i], 'href="/search.php?q=') Then
			$mparr = StringSplit($pagearr[$i], 'href=',1)
			;_arraydisplay($mparr, 'Multi page results')
			For $o = 1 to $mparr[0]
				If StringInstr($mparr[$o], '/search.php?q=') then
					$sUrl = Stringreplace(StringMid($mparr[$o], StringINStr($mparr[$o], '/search.php?'), StringinStr($mparr[$o], '">') - StringINStr($mparr[$o], '/search.php?')), 'amp;','')
					$fUrl = $rootUrl & $sUrl
					;Msgbox(0, 'preparing SecScrape', $fUrl)
					$urlarr = ScrapeSecondaryResults($fUrl, $urlarr)
					;if Ubound($retarr) > Ubound($urlarr) Then
					;	$urlarr = ''
					;	$urlarr = $retarr
					;Endif
					;_ArrayDisplay($urlarr, 'returned Updated urlarr')
					$sUrl = ''
					$fUrl = ''

				Endif
			Next
		Else

		Endif
	Next
	SplashOff()
	;_ArrayDisplay($urlarr, 'URLarr')
	;Msgbox(0,'ubound Urlarr', Ubound($urlarr))
	For $i = 1 to Ubound($urlarr) -1
	_GUICtrlListView_AddItem($List2, $urlarr[$i][0])

	_GUICtrlListView_AddSubItem($List2, _GUICtrlListView_GetItemCount($List2) -1, $urlarr[$i][1], 1)
	Next

	Redim $urlarr[1][2]

	_GUICtrlListView_SetColumnWidth($List2, 0, $LVSCW_AUTOSIZE)

;ScrapeSearchresults($pagearr)
GuiCtrlSetState($Search, $GUI_DISABLE)
EndFunc


Func ScrapeSecondaryResults($scrapeurl, $scrapearr)
	Local $dUrl, $tit, $pgarr, $rtUrl = 'http://www.dvdxml.com', $shtml

	$oIE.Navigate($scrapeurl)
	_IELoadWait($oIE)
	$shtml = _IEBodyReadHTML($oIE)
	$pgarr = StringSPlit($shtml, @CR)

	For $i = 1 to $pgarr[0]
		If StringInStr($pgarr[$i], '<A href="/download/view.php?xml_id=') Then
			;Msgbox(0,'SecScrapeFuction',$pgarr[$i])
			;"<a href='/download/view.php?xml_id=61239'>The Adventures of Indiana Jones: The Complete DVD Movie Collection [WS] [4 Discs]</a></"
			$dUrl = StringMid($pgarr[$i], StringInStr($pgarr[$i],'<a href="') + 9, (StringInStr($pgarr[$i], '">')) - (StringInStr($pgarr[$i],'<a href="') + 9))
			$tit = Stringreplace(StringReplace(StringMid($pgarr[$i],StringInStr($pgarr[$i], '">') + 2, (StringInStr($pgarr[$i], '</A></')) -(StringInStr($pgarr[$i], '">') + 2)),"&amp;", ''), "</A>", "")
			$downUrl = $rtUrl & $dUrl
			;_GUICtrlListView_AddItem($List2, $title)
			;_GUICtrlListView_AddSubItem($List2, _GUICtrlListView_GetItemCount($List2) -1, $downloadUrl, 1)
			Redim $scrapearr[Ubound($scrapearr) +1][2]
			$scrapearr[Ubound($scrapearr)-1][0] = $tit
			$scrapearr[Ubound($scrapearr)-1][1] = $downUrl
			$tit = ''
			$downUrl = ''
		Endif
	Next
	;_ArrayDisplay($scrapearr, 'Scrape array function')
	Return $scrapearr
EndFunc



Func Login()
	$user = GuiCtrlRead($UserInput);read USername
	$pass = GuiCtrlRead($PassInput);read Password
	If $user = '' or $pass = '' then
		return SetError(1)
	Endif
	SplashTextOn("Search", 'Logging in...',500,50,-1,-1,32,'Arial',10)
	; We prepare the Internet Explorer as our test subject
	Global $oIE = ObjCreate("InternetExplorer.Application.1")
	With $oIE
		.Visible=0
		.Top = (@DesktopHeight-400)/2
		.Height=400         ; Make it a bit smaller than our GUI.
		.Width=600
		.Silent=1           ; Don't show IE's dialog boxes
		$IEWnd=HWnd(.hWnd)  ; Remember the Window, in case user decides to close it
	EndWith
	; We choose for a specific Internet Explorer interface 'DWebBrowserEvents' because the IE is subject
; to modifications by e.g. Visual Studio and Adobe Acrobat Reader. If you have IE-plugins installed,
; AutoIt might not be able to find the correct interface automatically.
	$EventObject=ObjEvent($oIE,"IEEvent_","DWebBrowserEvents")
	if @error then
	   Msgbox(0,"AutoIt COM Test", _
		"ObjEvent: Can't use event interface 'DWebBrowserEvents'. Error code: " & hex(@error,8))
	   exit
	endif
	$Url = 'http://www.dvdxml.com'
	$oIE.Navigate($URL)
	_IELoadWait($oIE)

	$userfield = _IEGetObjByname ($oIE, "username")
	$passfield = _IEGetObjByname ($oIE, "userpass")
	$loginbutton = _IEGetObjByname ($oIE, "userlogin")
	;If IsObj($userfield) then msgbox(0, '', 'Userfield is onject!')
	_IEFormElementSetValue ( $userfield, $user)
	_IEFormElementSetValue ( $passfield, $pass)
	_IEAction ( $loginbutton, "click" )
	_IELoadWait($oIE)
	$lhtml = _IEBodyReadHTML($oIE)
	$pagrr = StringSPlit($lhtml, @CR)
	for $i = 1 to $pagrr[0]
		if StringInStr($pagrr[$i], 'Incorrect login') then
			$LoggedIn = False
			SplashOff()
			Return SetError(1)
		Endif
	Next

	$LoggedIn = True
	Return
EndFunc

Func makeXML($urlPath)
	Local $xmlarr[6],$DVDID,$title

	$slitem = _GUICtrlListView_GetSelectedIndices($list1,True)
	$title =_GUICtrlListView_GetItemText($List1, $slitem[1])
	SplashTextOn("Search", 'Preparing '& $title & '.DVDID.XML...',500,50,-1,-1,32,'Arial',10)
	$DVDID = GetDVDID($urlPath)
	SplashOff()
	$xmlarr[0] = 5
	$xmlarr[1] = '<?xml version="1.0" encoding="utf-8"?>'
	$xmlarr[2] = '<Disc>'
	$xmlarr[3] = '		<Name>' & $title & '</Name>'
	$xmlarr[4] = '		<ID>' & $DVDID & '</ID>'
	$xmlarr[5] = '</Disc>'
	$temppath =_GuiCtrlListView_GetItemText($list1, $slitem[1],1)
	If $temppath <> '' then
		$savepath = StringLeft($temppath, StringInStr($temppath, '\',-1,-1) -1)
	Else
		$savepath = 'My Documents'
	Endif

	$xmlfile = FileSaveDialog('Save XML file...',$savepath, "XML (*.XML)",2,$title & '.DVDID.xml')
	$temppath = ''
	$savepath = ''
	If not @error then
		_FileWriteFromArray($xmlfile, $xmlarr,  1)
		_GUICtrlListView_DeleteAllItems($list2)
		msgbox(64, 'Success', 'DVDID file successfully created')
		Select
		Case _GUICtrlListView_GetItemCount($list1) > 1

			For $i = ($slItem[1] +1) to _GUICtrlListView_GetItemCount($list1)
				If _GuiCtrlListView_GetItemChecked($list1, $i) = 1 Then
					_GUICtrlListView_SetItemSelected($list1, $i)
					Search(_GUICtrlListView_GetItemText($list1,$i))
					ExitLoop
				EndIf
			Next
		Case _GUICtrlListView_GetItemCount($list1) = 1
			_GUICtrlListView_DeleteAllItems($list1)
		EndSelect
		GuiCtrlSetState($Search, $GUI_ENABLE)
		$xmlarr = ''
	Else
		Msgbox(0,'Error', 'XML file Save Error. Try your search again.')
	Endif

EndFunc

Func GetDVDID($URL)

	Local $html, $pagearr, $DVDID
	$oIE.Navigate($url)
	_IELoadWait($oIE)
	$html = _IEBodyReadHTML($oIE)
	$pagearr = StringSPlit($html, @CR)
	;_ArrayDisplay($pagearr, 'GetDVDArr')

	For $i = 1 to $pagearr[0]
		If StringInStr($pagearr[$i], 'Dvdid:') Then
			$DVDID = StringStripWS(StringMId($pagearr[$i], StringInStr($pagearr[$i], "Dvdid: </b>") + 11, (StringInStr($pagearr[$i], "</td>"))-(StringInStr($pagearr[$i], "Dvdid: </b>") + 11)),3)
			ExitLoop
		Endif
	Next

	return $DVDID

ENdFunc

;Search Function
Func FileSearch($current)

    Local $search = FileFindFirstFile($current & "\*.*")
    While 1
        Dim $file = FileFindNextFile($search)
        If @error Or StringLen($file) < 1 Then ExitLoop


			;Add avi files to the array *.avi;*.dvr-ms;*.vob;*.mkv;*.mts;*.mpg
			If Not StringInStr(FileGetAttrib($current & "\" & $file), "D") And ($file <> "." Or $file <> "..") And (StringRight($file, 3) = "AVI" or StringRight($file, 5) = "dvr-ms" or StringRight($file, 3) = "mkv" or StringRight($file, 3) = "MTS" or StringRight($file, 3) = "MPG")Then

				$mTitle = StringMid($current & '\' & $file, StringInStr($current & '\' & $file, '\', -1,-1) +1, (StringInStr($current & '\' & $file, '.', -1,-1) -1) - (StringInStr($current & '\' & $file, '\', -1,-1)))
				_GUICtrlListView_AddItem($List1, $mTitle);Add the title of the file/movie
				_GUICtrlListView_SetItemChecked($List1, _GUICtrlListView_GetItemCount($list1) -1)
				_GUICtrlListView_AddSubItem($List1,_GUICtrlListView_GetItemCount($list1) -1,$current & "\" & $file,1);Add the path to the movie file

			EndIf


			If StringInStr(FileGetAttrib($current & "\" & $file), "D") And ($file <> "." Or $file <> "..") Then

				FileSearch($current & "\" & $file)

			EndIf
    WEnd
    FileClose($search)

EndFunc

Func SearchSplit()


EndFunc

Func OnExit()
	_IEQuit($oIE)
EndFunc
